import {Global, Module} from '@nestjs/common';
import * as mysql from "mysql2/promise";
import {drizzle} from "drizzle-orm/mysql2";
import {Logger} from "drizzle-orm/logger";
import {ConfigService} from "@nestjs/config";
// @Module({
//   providers: [DrizzleService],
//   exports: [DrizzleService],
// })
// export class DrizzleModule {}
class customLogger implements Logger{
  // 记录查询日志（最常用）
  logQuery(query: string, params: unknown[]): void {
    console.log(`[SQL] ${query}`); // 打印 SQL 语句
    console.log(`[Params] ${JSON.stringify(params)}`); // 打印参数
  }

  // 记录查询错误（可选实现）
  logQueryError(error: string, query: string, params: unknown[]): void {
    console.error(`[SQL Error] ${error}`);
    console.error(`[Failed Query] ${query}`);
  }

  // 记录查询执行时间（可选实现）
  logQuerySlow(duration: number, query: string, params: unknown[]): void {
    console.warn(`[Slow Query] ${duration}ms - ${query}`);
  }
};
@Module({
  providers: [
    {
      provide: 'DRIZZLE_ORM',
      inject: [ConfigService],
      async  useFactory(configService: ConfigService)  {
        try {
          // 使用 mysql2 的正确方式创建连接池
          const pool = mysql.createPool({
            host: configService.get('db.mysql.host'),
            port: configService.get('db.mysql.post'),
            user: configService.get('db.mysql.user'),
            password: configService.get('db.mysql.password'),
            database:configService.get('db.mysql.database'),
            // 添加额外配置以提高稳定性
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0
          });

          // 测试连接
          await pool.getConnection();
          console.log('数据库连接成功！');

          // 使用 drizzle 创建数据库实例，并传递日志记录器开启logger 可以看到请求接口的原生sql
          return  drizzle(pool, { logger:new customLogger(), });
        } catch (error) {
          console.error('数据库连接错误:', error);
          throw error;
        }
      }
    }

  ],
  exports: ['DRIZZLE_ORM'],
})
export class DrizzleModule {}
